package 排序算法;

public class bobbleDemo {
    static int[] arr1 = {3,5,1,-2,9,8};
    static int[] arr2 = {-2,1,3,5,8,9};
    public static void main(String[] args) {
        boolean b = TrueOrFalse();
        if(b){
            Speed();
        }else{
            bobbleSort(arr1);
            print(arr1);
        }
    }



    /*
     * 冒泡排序 时间复杂度O(n^2)
     * */
    private static void bobbleSort(int[] arr) {
        // (arr.length - 1) n个元素,最多比较n-1次
        for (int i = 0; i < arr.length - 1; i++) {
            boolean flag = true;
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    flag = false;
                    int temp = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = temp;
                }
            }
            // 在排序过程中,没有发生一次交换,表明已经有序,直接跳出循环
            if (flag) {
                break;
            }
        }
    }

    public static boolean TrueOrFalse(){
        bobbleSort(arr1);
        for (int i = 0; i < arr1.length; i++) {
            if(arr1[i] != arr2[i]){
                return false;
            }
        }
        return true;
    }
    public static void print(int [] arr){
        for (int j : arr) {
            System.out.print(j + " ");
        }
        System.out.println();
    }
    private static void Speed() {
        int[] arr2 = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr2[i] = (int)(Math.random()*80000);
        }
        long begin = System.currentTimeMillis();
        bobbleSort(arr2);
        long end = System.currentTimeMillis();
        System.out.println((end-begin));
    }
}
